package hqu.cst.xah.service.imp;


import hqu.cst.xah.mapper.OrderMapper;
import hqu.cst.xah.mapper.ProductMapper;
import hqu.cst.xah.pojo.Order;
import hqu.cst.xah.pojo.Product;
import hqu.cst.xah.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderServiceImp implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ProductMapper productMapper;


    @Override
    @Transactional
    public void createOrder(Order order) {
        Product product = productMapper.selectById(order.getProductId());
        if (product != null && product.getStock() >= order.getQuantity()) {
            product.setStock(product.getStock() - order.getQuantity());

            productMapper.updateById(product); // 更新产品信息
            orderMapper.insert(order);
        } else {
            // 处理库存不足的情况，如抛出异常
            throw new RuntimeException("订单库存数量不足: " +
                    order.getProductId());
        }
    }

    @Override
    @Transactional
    public void updateOrder(Order order) {
        // 查询订单是否存在
        Order existingOrder = orderMapper.selectById(order.getId());
        if (existingOrder == null) {
            throw new RuntimeException("没有查询到对应的订单: " + order.getId());
        }

        // 如果数量变化，更新库存
        if (!order.getQuantity().equals(existingOrder.getQuantity())) {
            // 查询对应的产品信息
            Product product = productMapper.selectById(existingOrder.getProductId());
            if (product == null) {
                throw new RuntimeException("没有查询到对应的产品: " + existingOrder.getProductId());
            }

            // 计算库存变化
            int stockChange = order.getQuantity() - existingOrder.getQuantity();

            // 检查库存是否充足
            if (product.getStock() - stockChange < 0) {
                throw new RuntimeException("库存不足，无法更新订单: 产品ID " + product.getId());
            }

            // 更新产品库存
            product.setStock(product.getStock() - stockChange);
            productMapper.updateById(product);
        }

        // 更新订单
        orderMapper.updateById(order);
    }

}
